// 校验类
import { AbstractControl, ValidatorFn, Validators } from "@angular/forms";
import { Console } from "console";
import { NzSafeAny } from "ng-zorro-antd/core/types";
export type MyErrorsOptions = { 'zh-cn': string; en: string } & Record<string, NzSafeAny>;
export type MyValidationErrors = Record<string, MyErrorsOptions>;


export class MyValidators extends Validators {

  // 最小长度校验
  static override minLength(minLength: number): ValidatorFn {
    return (control: AbstractControl): MyValidationErrors | null => {
      if (Validators.minLength(minLength)(control) === null) {
        return null;
      }
      return { minlength: { 'zh-cn': `最小长度为 ${minLength}`, en: `MinLength is ${minLength}` } };
    };
  }

  // 最大长度校验
  static override maxLength(maxLength: number): ValidatorFn {
    return (control: AbstractControl): MyValidationErrors | null => {
      if (Validators.maxLength(maxLength)(control) === null) {
        return null;
      }
      return { maxlength: { 'zh-cn': `最大长度为 ${maxLength}`, en: `MaxLength is ${maxLength}` } };
    };
  }

  // 手机号码格式校验
  static phone(control: AbstractControl): MyValidationErrors | null {
    const value = control.value;
    const phone = /^1([3589][0-9]|4[456789]|66|7[0135678]|9[189])\d{8}$/;

    return typeof value === 'string' && phone.test(value)
      ? null
      : { phone: { 'zh-cn': `请输入正确的号码格式`, en: `phone number is not valid` } };
  }

  // 密码格式校验
  static password(control: AbstractControl): MyValidationErrors | null {
    const value = control.value;
    const password = /^(?=.[A-Za-z])(?=.\d)[A-Za-z\d]{6,10}$/;
    console.log(password.test(value))

    return typeof value === 'string' && password.test(value)
      ? null
      : { password: { 'zh-cn': `6-10大小写字母和数字`, en: `password is not valid` } };
  }

}

